<template>
  <view class="page-container">
    <!-- 固定头部导航栏 -->
    <view class="fixed-header" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="nav-bar">
        <view class="title">对话</view>
        <view class="add-btn" @tap="gotoCreate">
          <text class="iconfont icon-plus" />
        </view>
      </view>
    </view>

    <!-- 可滚动的列表区域 -->
    <scroll-view 
      class="scrollable-content"
      :style="{ top: `calc(${statusBarHeight}px + 88rpx)` }"
      scroll-y 
      @scrolltolower="loadMore" 
      refresher-enabled
      :refresher-triggered="refreshing"
      :refresher-threshold="100"
      refresher-background="#f5f5f5"
      @refresherrefresh="refresh"
    >
      <!-- 未登录状态显示登录提示 -->
      <view v-if="!isLoggedIn" class="login-prompt">
        <image 
          class="prompt-image" 
          src="/static/welcome.png" 
          mode="aspectFit"
        />
        <text class="prompt-title">欢迎使用糯米智能</text>
        <text class="prompt-desc">登录后可以体验更多功能</text>
        <button class="login-btn" @tap="gotoLogin">
          <text class="iconfont icon-wechat"></text>
          <text>立即登录</text>
        </button>
      </view>

      <!-- 已登录状态显示设备列表 -->
      <template v-else>
        <view v-for="item in deviceList" :key="item.id">
          <uni-swipe-action>
            <uni-swipe-action-item 
              :right-options="swipeOptions" 
              @click="handleSwipeClick($event, item)"
            >
              <view class="device-item" @tap="gotoChat(item)">
                <view class="action">
                  <image 
                    class="avatar" 
                    :src="item.icon || '/static/avatar.jpg'" 
                    mode="aspectFill" 
                  />
                </view>
                <view class="content">
                  <view class="title-row">
                    <text class="name">{{ item.name }}</text>
                    <text class="tag" v-if="item.tag">{{ item.tag }}</text>
                  </view>
                  <text class="desc">{{ item.description }}</text>
                </view>
              </view>
            </uni-swipe-action-item>
          </uni-swipe-action>
        </view>
      </template>
    </scroll-view>

    <!-- 固定底部导航 -->
    <view class="fixed-footer">
      <view class="tab-bar">
        <view 
          v-for="(tab, index) in tabs" 
          :key="index" 
          class="tab-item" 
          :class="{ active: currentTab === index }"
          @tap="switchTab(index)"
        >
          <text class="iconfont" :class="tab.icon" />
          <text class="text">{{ tab.text }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/modules/user'
import { useDeviceStore } from '@/stores/modules/device'
import { system } from '@/utils/system'
import { storage } from '@/utils/storage'

const userStore = useUserStore()
const deviceStore = useDeviceStore()

// 添加删除相关的响应式变量和方法
const deleteButtonWidth = 160 // 删除按钮宽度，单位 rpx

// 状态栏高度
const statusBarHeight = system.getStatusBarHeight()

// 用户信息和登录状态
const userInfo = computed(() => userStore.userInfo)
const isLoggedIn = computed(() => !!userStore.userInfo)

// 当前日期
const currentDate = computed(() => {
    const date = new Date()
    return `${date.getFullYear()} 年 ${date.getMonth() + 1} 月 ${date.getDate()} 日`
})

// 底部导航配置
const tabs = [{
        text: '对话',
        icon: 'icon-message'
    },
    {
        text: '发现',
        icon: 'icon-search'
    },
    {
        text: '创建',
        icon: 'icon-add'
    },
    {
        text: '通知',
        icon: 'icon-notification'
    },
    {
        text: '我的',
        icon: 'icon-user'
    }
]
const currentTab = ref(0)

// 设备列表数据
const deviceList = computed(() => deviceStore.privateDevices || [])
const recommendDevice = computed(() => {
    const publicDevices = deviceStore.publicDevices || []
    return publicDevices[0] || null
})
const loading = ref(false)
const refreshing = ref(false)

// 跳转到登录页面
const gotoLogin = () => {
    uni.navigateTo({
        url: '/pages/login/login'
    })
}

// 检查登录状态
const checkLogin = async (requireLogin = false) => {
    const loggedIn = userStore.checkLoginStatus()
    if (!loggedIn && requireLogin) {
        gotoLogin()
        return false
    }
    if (loggedIn && !userStore.userInfo) {
        try {
            await userStore.getUserInfo()
        } catch (error) {
            console.error('获取用户信息失败:', error)
            if (requireLogin) {
                gotoLogin()
                return false
            }
        }
    }
    return loggedIn
}

// 加载数据
const loadData = async () => {
    if (loading.value) return
    loading.value = true

    try {
        const isLoggedIn = await checkLogin(false)
        if (isLoggedIn) {
            await Promise.all([
                deviceStore.loadPrivateDevices(),
                deviceStore.loadPublicDevices({
                    current: 1,
                    size: 10
                })
            ])
        }
    } catch (error) {
        console.error('加载失败:', error)
        uni.showToast({
            title: error.message || '加载失败',
            icon: 'none'
        })
    } finally {
        loading.value = false
    }
}

// 下拉刷新处理
const refresh = async () => {
    if (refreshing.value) return
    refreshing.value = true
    
    try {
        await loadData()
    } catch (error) {
        console.error('刷新失败:', error)
        uni.showToast({
            title: '刷新失败',
            icon: 'none'
        })
    }

    setTimeout(() => {
        refreshing.value = false
        uni.stopPullDownRefresh()
    }, 800)
}

// 加载更多
const loadMore = async () => {
    if (loading.value || !isLoggedIn.value) return
    loading.value = true

    try {
        const currentPage = Math.ceil((deviceStore.publicDevices?.length || 0) / 10) + 1
        await deviceStore.loadPublicDevices({
            current: currentPage,
            size: 10
        })
    } catch (error) {
        console.error('加载更多失败:', error)
        uni.showToast({
            title: '加载失败',
            icon: 'none'
        })
    } finally {
        loading.value = false
    }
}

// 切换标签页
const switchTab = (index) => {
    const routes = [
        '/pages/index/index',
        '/pages/discover/discover',
        '/pages/create/create',
        '/pages/notification/notification',
        '/pages/my/my'
    ]
    uni.switchTab({
        url: routes[index]
    })
}

// 定义滑动按钮选项
const swipeOptions = [
    {
        text: '删除',
        style: {
            backgroundColor: '#ff3b30'
        }
    }
]

// 处理滑动按钮点击
const handleSwipeClick = async (event, item) => {
    if (!isLoggedIn.value) {
        uni.showModal({
            title: '提示',
            content: '登录后才能删除智能体，是否立即登录？',
            success: (res) => {
                if (res.confirm) {
                    gotoLogin()
                }
            }
        })
        return
    }

    try {
        uni.showModal({
            title: '确认删除',
            content: '确定要删除这个智能体吗？',
            success: async (res) => {
                if (res.confirm) {
                    await deviceStore.deleteDevice(item.id)
                    uni.showToast({
                        title: '删除成功',
                        icon: 'success'
                    })
                }
            }
        })
    } catch (error) {
        console.error('删除失败:', error)
        uni.showToast({
            title: error.message || '删除失败',
            icon: 'none'
        })
    }
}

// 跳转到聊天页面
const gotoChat = (device) => {
    if (device.requireLogin && !isLoggedIn.value) {
        uni.showModal({
            title: '提示',
            content: '登录后才能开始对话，是否立即登录？',
            success: (res) => {
                if (res.confirm) {
                    gotoLogin()
                }
            }
        })
        return
    }
    
    console.log('跳转到聊天页面,设备ID:', device.id)
    uni.navigateTo({
        url: `/pages/chat/chat?id=${device.id}`
    })
}

// 跳转到创建页面
const gotoCreate = () => {
    if (!isLoggedIn.value) {
        uni.showModal({
            title: '提示',
            content: '登录后才能创建智能体，是否立即登录？',
            success: (res) => {
                if (res.confirm) {
                    gotoLogin()
                }
            }
        })
        return
    }

    uni.navigateTo({
        url: '/pages/create/create'
    })
}

// 在页面加载时加载数据
onMounted(() => {
    loadData()
})
</script>


<style lang="scss">
.page-container {
  width: 100vw;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  background: #fff;
  
  .fixed-header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
    background: #fff;
    border-bottom: 1px solid #f5f5f5;

    .nav-bar {
      height: 88rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 30rpx;

      .title {
        font-size: 36rpx;
        font-weight: 600;
        color: #333;
      }

      .add-btn {
        width: 44rpx;
        height: 44rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        .iconfont {
          font-size: 44rpx;
          color: #333;
        }
      }
    }
  }

   .scrollable-content {
     position: fixed;
     left: 0;
     right: 0;
     bottom: calc(110rpx + env(safe-area-inset-bottom));
     overflow-y: auto;
     -webkit-overflow-scrolling: touch;
     background: #fff;
   
     .device-item {
       padding: 24rpx 30rpx;
       display: flex;
       align-items: flex-start;
       background: #fff;
       border-bottom: 1px solid #f5f5f5;
   
       .action {
         flex-shrink: 0;
         margin-right: 20rpx;
   
         .avatar {
           width: 100rpx;
           height: 100rpx;
           border-radius: 12rpx;
         }
       }
   
       .content {
         flex: 1;
         min-width: 0;
         margin-top: 4rpx;
   
         .title-row {
           margin-bottom: 12rpx;
           display: flex;
           align-items: center;
   
           .name {
             flex: 1;
             font-size: 32rpx;
             font-weight: 500;
             color: #333;
             overflow: hidden;
             text-overflow: ellipsis;
             white-space: nowrap;
           }
         }
   
         .desc {
           font-size: 26rpx;
           color: #999;
           overflow: hidden;
           text-overflow: ellipsis;
           white-space: nowrap;
           line-height: 1.4;
         }
       }
     }
   }
   // 添加登录提示样式
   .login-prompt {
     padding: 60rpx;
     display: flex;
     flex-direction: column;
     align-items: center;
     margin-top: 120rpx;
   
     .prompt-image {
       width: 240rpx;
       height: 240rpx;
       margin-bottom: 40rpx;
     }
   
     .prompt-title {
       font-size: 36rpx;
       font-weight: 600;
       color: #333;
       margin-bottom: 16rpx;
     }
   
     .prompt-desc {
       font-size: 28rpx;
       color: #999;
       margin-bottom: 48rpx;
     }
   
     .login-btn {
       width: 480rpx;
       height: 88rpx;
       background: #00C251;
       border-radius: 44rpx;
       color: #fff;
       font-size: 32rpx;
       display: flex;
       align-items: center;
       justify-content: center;
       border: none;
       box-shadow: 0 8rpx 16rpx rgba(0, 194, 81, 0.2);
   
       &::after {
         border: none;
       }
   
       .iconfont {
         font-size: 40rpx;
         margin-right: 8rpx;
       }
     }
   }
   
   
  .fixed-footer {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 100;
    
    .tab-bar {
      height: 110rpx;
      background: #fff;
      display: flex;
      align-items: center;
      border-top: 1rpx solid #eee;
      padding-bottom: env(safe-area-inset-bottom);

      .tab-item {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        color: #999;

        .iconfont {
          font-size: 48rpx;
          margin-bottom: 6rpx;
        }

        .text {
          font-size: 24rpx;
        }

        &.active {
          color: #007AFF;
        }
      }
    }
  }
}
</style>